import MaskText from '@/components/MaskText';
import Ellipsis from '../../../components/Ellipsis';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import PateoModalForm from '../../../components/common/PateoModalForm';
import styles from './index.less';
import { filterAuth } from '@/support/common';
import { transferOption } from '@/utils/common';
import { PlusOutlined } from '@ant-design/icons';
import { Card, Table, Button, message, Select } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import React, { Component, Fragment } from 'react';
import router from 'umi/router';

const mapStateToProps = (state: any) => ({
  contentMng: state.contentMng,
  menu: state.menu,
  loading: state.loading.models['contentMng'],
});
class ContentMngList extends Component<any, any> {
  state = {
    modalVisible: false,
    postUrl: '',
    formData: {
      brandCode: '',
      contentItemName: '',
      contentDescription: '',
    },
    filterData: {
      brandCode: '',
    },
    brandOptions: [],
    projectData: [],
  };

  async componentDidMount() {
    await this.fetchProjectIdAndBrandCode();
    this.fetchContentList();
  }

  async fetchProjectIdAndBrandCode() {
    const { dispatch } = this.props;
    return Promise.all([
      dispatch({
        type: 'basedata/brandFetch',
        callback: res => {
          const brandOptions = res?.data ?? [];
          if (brandOptions.length >= 1) {
            this.setState({
              filterData: {
                brandCode: brandOptions[0]?.brandCode,
              },
            });
          }

          this.setState({ brandOptions });
        },
      }),
      dispatch({
        type: 'basedata/findProjectIdByBrandCode',
        callback: res => this.setState({ projectData: res?.data ?? [] }),
      }),
    ]);
  }

  getProjectId(brandCode: string) {
    const { projectData } = this.state;
    if (!brandCode) {
      return '';
    }
    return projectData.find(item => item.brandCode === brandCode)?.projectId ?? '';
  }

  fetchContentList = (payload = {}) => {
    const { dispatch } = this.props;
    const { filterData } = this.state;
    dispatch({
      type: 'contentMng/queryList',
      payload: {
        ...filterData,
        projectId: this.getProjectId(filterData.brandCode),
        ...payload,
      },
    });
  };

  handleAdd = () => {
    const { filterData } = this.state;
    this.setState({
      modalVisible: true,
      selectedId: null,
      formData: {
        ...this.state.formData,
        brandCode: filterData.brandCode,
      },
    });
  };

  handleEdit = (data: any) => {
    this.setState({
      modalVisible: true,
      formData: { ...data },
      selectedId: data.sid,
    });
  };

  handleFreshPage = () => {
    const {
      contentMng: {
        contentData: { pagination },
      },
    } = this.props;
    const { current, pageSize } = pagination;
    let params = { current: current, pageSize: pageSize };
    this.fetchContentList(params);
  };
  // 分页时触发
  tableOnChange = (pagination: any) => {
    const current = pagination.current;
    const params = {
      current: current,
      pageSize: pagination.pageSize,
    };
    this.fetchContentList(params);
  };
  handleSubmit = (val: any) => {
    const {
      menu: { userProfile },
      dispatch,
    } = this.props;
    const { formData } = this.state;

    // 数据为空处理
    for (let v in val) {
      if (!val[v] || !val[v].toString().trim()) {
        val[v] = undefined;
      }
    }

    this.setState({ formData: val });
    // 组合formData以及当前表单的值  解构赋值不改变原对象
    const pushData = { ...formData, ...val, projectId: this.getProjectId(val.brandCode) };
    const url = formData?.sid ? 'contentMng/editContentItem' : 'contentMng/addContentItem';
    formData?.sid && (pushData['updateBy'] = userProfile.accountName);
    dispatch({
      type: url,
      payload: { ...pushData },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          message.success(formData?.sid ? '编辑成功' : '新增成功');
          this.setState({
            formData: {
              ...this.state.formData,
              contentItemName: '',
              contentDescription: '',
            },
            modalVisible: false,
          });
          this.setState({ loading: false });
          // 重新查询列表区分是否属于新增，编辑
          this.handleFreshPage();
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };
  handleDelete = (sid: string) => {
    this.setState({ selectedId: sid });
    const { dispatch } = this.props;
    dispatch({
      type: 'contentMng/delContentItem',
      payload: { sid },
      callback: (response: any) => {
        if (response.statusCode === '0') {
          message.success('删除成功');
          this.setState({ selectedId: null });
          this.handleFreshPage();
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };
  closeEditModal = () => {
    this.setState({
      modalVisible: false,
      selectedId: null,
    });
  };
  onBrandSelect = (brandCode: string) => {
    this.setState(
      {
        filterData: {
          ...this.state.filterData,
          brandCode,
        },
      },
      this.fetchContentList,
    );
  };
  getFormItems() {
    const { filterData, brandOptions } = this.state;
    return [
      {
        type: 'input',
        title: '内容项名称',
        key: 'contentItemName',
        rules: [{ required: true, message: '请输入内容项名称', whitespace: true }],
        maxLength: 200,
        autoComplete: 'off',
      },
      {
        type: 'select',
        title: '品牌',
        key: 'brandCode',
        editDisabled: true,
        rules: [{ required: true, message: '请选择品牌', whitespace: true }],
        selectOptions: brandOptions,
        keyValue: ['brandCode', 'brandName'],
        defaultValue: filterData.brandCode,
        allowClear: false,
        maxLength: 200,
      },
      {
        type: 'textArea',
        title: '内容说明',
        key: 'contentDescription',
        maxLength: 2000,
      },
    ];
  }
  render() {
    const {
      menu: { permissions },
      location: { pathname = '/' },
      loading,
      contentMng: {
        contentData: { contentList = [], pagination },
      },
    } = this.props;

    const { modalVisible, formData, brandOptions } = this.state;
    const columns: Array<any> = [
      {
        title: '序号',
        dataIndex: 'no',
        width: 60,
        render: (text: any, record: any, index: any) => {
          return index + 1 + (pagination.current - 1) * pagination.pageSize;
        },
      },
      {
        title: '内容项名称',
        dataIndex: 'contentItemName',
        render: (text: any) => {
          return (
            <Ellipsis length={10} tooltip>
              {text}
            </Ellipsis>
          );
        },
      },
      {
        title: '内容项说明',
        dataIndex: 'contentDescription',
        render: (text: any) => {
          return (
            <Ellipsis length={25} tooltip overlayInnerStyle={{ height: '100px', overflow: 'auto' }}>
              {text}
            </Ellipsis>
          );
        },
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        render: (text: any) => {
          return moment(text).format('YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        title: '创建人',
        dataIndex: 'createBy',
        render(val: any) {
          return <MaskText text={val} type="name" />;
        },
      },
      {
        title: '操作',
        dataIndex: '操作',
        key: 'opt',
        width: 150,
        render: (text: any, content: any) => {
          const btns = [
            {
              title: '编辑',
              key: 'edit',
              auth: 'contentItem_doEdit',
              onConfirm: (e: any) => {
                e.stopPropagation();
                this.handleEdit(content);
              },
            },
            {
              title: '删除',
              key: 'delete',
              auth: 'contentItem_doDel',
              Popconfirm: true,
              message: '是否确认删除？',
              onConfirm: (e: any) => {
                e.stopPropagation();
                this.handleDelete(content.sid);
              },
            },
          ];
          return <PateoAuthButtons btns={btns} max={1} pathname={pathname} />;
        },
      },
    ];

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };

    const formItems = this.getFormItems();
    return (
      <div className={styles.container}>
        <Card title="" bordered={false}>
          {filterAuth('contentItem_doAdd', permissions, pathname) ? (
            <div className="my_newItem">
              {brandOptions.length > 1 ? (
                <Fragment>
                  <span className="filter-item">品牌：</span>
                  <Select
                    className="filter-item"
                    placeholder="请选择品牌"
                    defaultValue={brandOptions[0]?.brandCode ?? ''}
                    onChange={this.onBrandSelect}
                  >
                    {transferOption(brandOptions, ['brandCode', 'brandName'])}
                  </Select>
                </Fragment>
              ) : null}

              <Button size="small" icon={<PlusOutlined />} type="primary" onClick={this.handleAdd}>
                新增
              </Button>
            </div>
          ) : null}
          <Table
            className={styles['customer-grid']}
            loading={loading}
            rowKey={row => row.sid}
            columns={columns}
            size="small"
            pagination={paginationProps}
            dataSource={contentList}
            onChange={this.tableOnChange}
            onRow={record => {
              return {
                onClick: event => {
                  sessionStorage.setItem('contentId', record.sid);
                  sessionStorage.setItem(
                    'contentItemInfo',
                    JSON.stringify({
                      contentId: record.sid,
                      projectId: record.projectId,
                    }),
                  );
                  router.push('/contentMng/contentTempList');
                }, // 点击行 跳转到内容模板列表页
              };
            }}
          />
        </Card>
        {modalVisible && (
          <PateoModalForm
            style={{ top: '10%' }}
            formItems={formItems}
            changeVisible={() => this.setState({ formData: {}, modalVisible: false })}
            formData={formData}
            visible={modalVisible}
            handleModalFieldsValue={this.handleSubmit}
            handleCallback={this.handleFreshPage}
            title={['新增内容项', '编辑内容项']}
          />
        )}
      </div>
    );
  }
}
export default connect(mapStateToProps)(ContentMngList);
